package la.bbs558.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @author: Shanks
 * @date: 2023/12/16 13:06
 * @desc:
 */
@Configuration
public class JacksonConfig {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> {
            builder.serializerByType(Long.class, new CustomLongSerializer());
            builder.serializerByType(Long.TYPE, new CustomLongSerializer());
        };
    }
}
class CustomLongSerializer extends JsonSerializer<Long> {

    private static final long MAX_SAFE_INT = 1L << 53;

    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (value > MAX_SAFE_INT || value < -MAX_SAFE_INT) {
            gen.writeString(value.toString());
        } else {
            gen.writeNumber(value);
        }
    }
}
